package com.atguigu.spzx.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.manager.mapper.SysUserMapper;
import com.atguigu.spzx.manager.service.SysUserService;
import com.atguigu.spzx.model.dto.system.LoginDto;
import com.atguigu.spzx.model.dto.system.SysUserDto;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.system.LoginVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author SNA
 * @date 2024/2/6
 * @description
 **/
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 用户登录
     * @param loginDto
     * @return
     */
    @Override
    public LoginVo login(LoginDto loginDto) {

        //校验验证码是否正确
        //1、获取页面输入的验证码和存储到Redis的key
        String captcha = loginDto.getCaptcha();
        String key = loginDto.getCodeKey();

        //根据codeKey查询Redis中的验证码
        String redisCode = redisTemplate.opsForValue().get("user:login:validatecode:" + key);

        //2、比较输入的验证码和存储到Redis的验证码是否一致
        if(StrUtil.isEmpty(captcha) || !StrUtil.equalsIgnoreCase(captcha, redisCode)) {
            throw new GuiguException(ResultCodeEnum.VALIDATECODE_ERROR);
        }

        //3、验证码一致，删除Redis中的验证码
        redisTemplate.delete("user:login:validatecode:" + key);


        //校验验证码一致后，就校验用户登录名和密码
        //1、获取提交的用户名，根据loginDto获取到
        String userName = loginDto.getUserName();

        //2、根据用户名查询数据库表 sys_user表
        SysUser sysUser = sysUserMapper.selectUserInfoByUserName(userName);

        //3、如果根据用户名查不到对应信息，则用户不存在，返回错误信息
        if(sysUser == null) {
//            throw new RuntimeException("用户名不存在");
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }

        //4、如果根据用户名查询到用户信息，用户存在
        //5、获取输入的密码，比较输入的密码和数据库密码是否一致
        String database_password = sysUser.getPassword();
        String input_password = DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes());
        //比较，如果密码不一致登录失败
        if(!database_password.equals(input_password)){
//            throw new RuntimeException("密码不正确");
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }

        //6、如果密码一致，登录成功
        //7、登录成功，生成用户唯一标识token
        String token = UUID.randomUUID().toString().replaceAll("-", "");

        //8、把登录成功用户信息放到Redis里面
        // key: token  value: 用户信息
        redisTemplate.opsForValue()
                .set("user:login:"+token,
                        JSON.toJSONString(sysUser),
                        7,
                        TimeUnit.DAYS);

        //9、返回loginvo对象
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);

        return loginVo;
    }


    /**
     * 获取当前登录用户信息
     */
    @Override
    public SysUser getUserInfo(String token) {
        String userJson = redisTemplate.opsForValue().get("user:login:" + token);
        SysUser sysUser = JSON.parseObject(userJson, SysUser.class);
        return sysUser;
    }

    //用户退出登录
    @Override
    public void logout(String token) {
        redisTemplate.delete("user:login:" + token);
    }

    // 分页查询用户列表
    @Override
    public PageInfo<SysUser> findByPage(SysUserDto sysUserDto, Integer pageNum, Integer pageSize) {
        // 设置分页插件，启动分页参数
        PageHelper.startPage(pageNum, pageSize);
        List<SysUser> list = sysUserMapper.findByPage(sysUserDto);
        PageInfo<SysUser> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    // 用户添加
    @Override
    public void saveSysUser(SysUser sysUser) {
        // 判断新增用户名是否重复
        SysUser dbSysUser = sysUserMapper.selectUserInfoByUserName(sysUser.getUserName());
        if(dbSysUser != null) {
            throw new GuiguException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }
        
        // 对密码进行加密
        String digestPassword = DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes());
        sysUser.setPassword(digestPassword);
        sysUser.setStatus(0);

        sysUserMapper.saveSysUser(sysUser);
    }

    // 用户修改
    @Override
    public void updateSysUser(SysUser sysUser) {
        sysUserMapper.updateSysUser(sysUser);
    }

    // 用户删除
    @Override
    public void deleteById(Long id) {
        sysUserMapper.deleteById(id);
    }
}
